#coding: utf-8
# post用户名和密码到http://jwgl.just.edu.cn:8080/jsxsd/xk/LoginToXk获取Location
# 获取Location

import requests
from bs4 import BeautifulSoup

s =requests.Session()

def login(username, password):
    url = 'http://jwgl.just.edu.cn:8080/jsxsd/xk/LoginToXk'
    data = {
        'USERNAME': username,
        'PASSWORD': password
    }
    headers = {
        'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
        'Accept-Encoding':'gzip, deflate',
        'Accept-Language':'zh-CN,zh;q=0.8',
        'Cache-Control':'no-cache',
        'Connection':'keep-alive',
        'Content-Length':'40',
        'Content-Type':'application/x-www-form-urlencoded',
        'Host':'jwgl.just.edu.cn:8080',
        'Origin':'http://jwgl.just.edu.cn:8080',
        'Pragma':'no-cache',
        'Referer':'http://jwgl.just.edu.cn:8080/jsxsd/xk/LoginToXk',
        'Upgrade-Insecure-Requests':'1',
        'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.116 Safari/537.36'
    }
    r = s.post(url, data, headers=headers)
    html = r.text.strip()
    return html  #<type 'unicode'>

# def get_gradequery_link():
#     html = login()
#     soup = BeautifulSoup(html, 'html5lib')
#     block7 = soup.select('a > div[class="block7"]')[0]
#     link = block7.parent['href'] #<type 'str'>
#     return link

def get_grade_html():
    url = 'http://jwgl.just.edu.cn:8080/jsxsd/kscj/cjcx_list'
    data = {
        'kksj': '',
        'kcxz': '',
        'kcmc': '',
        'xsfs': 'all'
    }
    headers = {
        'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
        'Accept-Encoding':'gzip, deflate',
        'Accept-Language':'zh-CN,zh;q=0.8',
        'Cache-Control':'no-cache',
        'Connection':'keep-alive',
        'Content-Length':'26',
        'Content-Type':'application/x-www-form-urlencoded',
        'Host':'jwgl.just.edu.cn:8080',
        'Origin':'http://jwgl.just.edu.cn:8080',
        'Pragma':'no-cache',
        'Referer':'http://jwgl.just.edu.cn:8080/jsxsd/kscj/cjcx_query',
        'Upgrade-Insecure-Requests':'1',
        'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.116 Safari/537.36'
    }
    r = s.post(url, data, headers=headers)
    html = r.text.strip()
    return html

def get_pyfa():
    url = 'http://jwgl.just.edu.cn:8080/jsxsd/pyfa/pyfazd_query'
    req = s.get(url)
    html = req.text.strip()
    soup = BeautifulSoup(html, 'lxml')
    dataList = soup.select('table > tr')
    dataList.pop(0)
    pyfa = []
    # print dataList
    for data in dataList:
        data = unicode(data)
        course = {}
        soup = BeautifulSoup(data, 'lxml')
        tds = soup.select('tr > td')
        course['date'] = tds[1].string
        course['id'] = tds[4].string
        course['name'] = tds[5].string
        course['credit'] = tds[7].string
        course['category'] = tds[8].string
        pyfa.append(course)
    return pyfa


def get_all_grade():
    html = get_grade_html()
    # print type(html)
    soup = BeautifulSoup(html, 'html5lib')
    # print soup.prettify()
    dataList = soup.select('tbody > tr')
    #两次删除list第一个元素
    dataList.pop(0)
    dataList.pop(0)
    course_list = []
    pyfa = get_pyfa()
    for data in dataList:
        course = {}
        data = unicode(data)
        soup = BeautifulSoup(data, 'lxml')
        # print soup
        tds = soup.select('tr > td')
        course['date'] = tds[1].string
        course['id'] = tds[2].string
        course['name'] = tds[3].string
        course['grade'] = tds[4].string
        for cou in pyfa:
            if cou['id'] == course['id']:
                course['credit'] = cou['credit']
                course['category'] = cou['category']
        course_list.append(course)
    return course_list

def different_semester_grade(date):
    print '您 '+str(date)+' 学期成绩如下: '
    course = get_all_grade()
    # print course
    for cou in course:
        if cou['date'] == date:
            print cou['name'].encode('utf-8').ljust(40), cou['grade'].encode('utf-8').ljust(10), cou['credit'].encode('utf-8').ljust(10), cou['category'].encode('utf-8').ljust(10)

# http://jwc.just.edu.cn/view/17/80.html
def calc_gpa(date):
    course = get_all_grade()
    gpa = 0
    credits = 0
    for cou in course:
        if cou['date'] == date:
            if cou['grade'].encode('utf-8') == '优':
                credits += float(cou['credit'])
                gpa += 4.5*float(cou['credit'])
            elif cou['grade'].encode('utf-8') == '良':
                credits += float(cou['credit'])
                gpa += 3.5*float(cou['credit'])
            elif cou['grade'].encode('utf-8') == '中':
                credits += float(cou['credit'])
                gpa += 2.5*float(cou['credit'])
            elif cou['grade'].encode('utf-8') == '及格':
                credits += float(cou['credit'])
                gpa += 1.5*float(cou['credit'])
            elif cou['grade'].encode('utf-8') == '不及格':
                credits += float(cou['credit'])
                gpa += 0
            elif cou['grade'].encode('utf-8') == '合格':
                credits += float(cou['credit'])
                gpa += 2.5*float(cou['credit'])
            elif cou['grade'].encode('utf-8') == '不合格':
                credits += float(cou['credit'])
                gpa += 0
            else:
                credits += float(cou['credit'])
                gpa = gpa + ((float(cou['grade'])/10) - 5)*float(cou['credit'])
    return gpa/credits
if __name__ == '__main__':
    # print get_main_page_html()
    # print get_gradequery_link()
    username = '1340903120'
    password = 'wdxyx19960618'
    login(username, password)
    date = '2015-2016-1'
    different_semester_grade(date)
    print calc_gpa(date)
    # print get_pyfa()
    # grades = get_all_grade()
    # for grade in grades:
    #     print grade
